import storage from 'store'
import { login } from '@/api/net';
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login ({ dispatch, commit },loginInfo) {
      return new Promise((resolve, reject) => {
        if(loginInfo){
          login(loginInfo).then(res => {
            storage.set('token', res.user.token, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', res.user.token)
            res.user['menu'] = res.menu;
            commit('SET_INFO', res.user)
            dispatch('GenerateRoutes',res.menu[0].children)
            .then(res=>{
              resolve()
            })
          }).catch(error => {
            reject(error)
          })
        }else{
          reject();
        }
      })
    },
    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        storage.remove(ACCESS_TOKEN)
        resolve()
      })
    }

  }
}

export default user
